package com.gogowan.agroenterprise.supply;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.FPhotoInfo;
import com.gogowan.agroenterprise.model.IntegrateQuestInfo;
import com.gogowan.agroenterprise.model.Message;
import com.gogowan.agroenterprise.model.PicturesInfo;
import com.gogowan.agroenterprise.model.ResultInfo;
import com.gogowan.agroenterprise.model.SupplyDemandDescInfo;
import com.gogowan.agroenterprise.utils.Utils;
import com.gogowan.agroenterprise.widget.PicturesGridView;

public class MyDemandDetailActivity extends BaseActivity{
	
	private EditText title;
	private EditText introduction;
	private EditText keywords;
	private EditText productInfo;
	private PicturesGridView picGrid;
	private Button datePicker;
	private String date;
	//private Button editBtn;
	private Button releaseBtn;
	
	private ProgressDialog progressDialog;
	
	private SharedPreferences preferences;
	private long enterpriseId;
	private long sdID;
	private List<FPhotoInfo> fPhotoInfos;
	private SupplyDemandDescInfo supplyDemandDescInfo; //传过来的信息
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.supply_my_demand_detail);
		
		title = (EditText)findViewById(R.id.my_demand_detail_title);
		introduction = (EditText)findViewById(R.id.my_demand_detail_introduction);
		keywords = (EditText)findViewById(R.id.my_demand_detail_keywords);
		productInfo = (EditText)findViewById(R.id.my_demand_detail_product_info);
		picGrid = (PicturesGridView)findViewById(R.id.my_demand_detail_pic_grid);
		datePicker = (Button)findViewById(R.id.my_demand_detail_dateBtn);
		releaseBtn = (Button)findViewById(R.id.my_demand_detail_save);
		
		title.setEnabled(true); title.setFocusableInTouchMode(true); title.requestFocus();
		introduction.setEnabled(true);introduction.setFocusableInTouchMode(true); introduction.requestFocus();
		keywords.setEnabled(true);keywords.setFocusableInTouchMode(true); keywords.requestFocus();
		productInfo.setEnabled(true);productInfo.setFocusableInTouchMode(true); productInfo.requestFocus();
		datePicker.setEnabled(true); datePicker.setFocusable(true);
		picGrid.setEnabled(true);picGrid.setFocusable(true);
		
		//设置第一个文本框为当前焦点
		title.setFocusable(true);
		title.requestFocus();
		title.setFocusableInTouchMode(true);
		
		preferences = getSharedPreferences("LoginINfo", MODE_PRIVATE);
		enterpriseId = preferences.getLong("enterpriseid", 0);
		
		initData();
		
		datePicker.setOnClickListener(dateBtnCallback);
		//editBtn.setOnClickListener(editBtnCallback);
		releaseBtn.setOnClickListener(releaseBtnCallback);
	}
	
	/**
	 * 初始化数据
	 */
	private void initData(){
		
		Intent intent = getIntent();
		String string = intent.getStringExtra("myDetail");
		
		supplyDemandDescInfo = (SupplyDemandDescInfo)Utils.fromJSON(string, SupplyDemandDescInfo.class);
		if (supplyDemandDescInfo == null) {
			return;
		} else {
			
			title.setText(supplyDemandDescInfo.getTitle().toString().trim());
			introduction.setText(supplyDemandDescInfo.getIntroduction().toString().trim());
			keywords.setText(supplyDemandDescInfo.getKeyWords().toString().trim());
			productInfo.setText(supplyDemandDescInfo.getDescription().toString());
			datePicker.setText(supplyDemandDescInfo.getTimeDown().toString().trim());
			
			sdID = supplyDemandDescInfo.getSdID();
			date = supplyDemandDescInfo.getTimeDown().toString().trim();
			
			
			List<FPhotoInfo> fPhotoInfos = supplyDemandDescInfo.getPhotoList();
			if (fPhotoInfos == null || fPhotoInfos.size() == 0) {
				
			} else {
				List<PicturesInfo> picturesInfos = new ArrayList<PicturesInfo>();
				for (int i = 0; i < fPhotoInfos.size(); i++) {
					PicturesInfo picturesInfo = new PicturesInfo();
					picturesInfo.setRequestUrl(fPhotoInfos.get(i).getPhotoPathSmall());
					picturesInfo.setPhotoNormal(fPhotoInfos.get(i).getPhotoNormal());
					picturesInfo.setPhotoSmall(fPhotoInfos.get(i).getPhotoSmall());
					picturesInfo.setDescription(fPhotoInfos.get(i).getPhotoDescription());
					picturesInfos.add(picturesInfo);
				}
				picGrid.setList(picturesInfos);
			}
			
		}
	}

	
	/**
	 * 删除按钮点击事件
	 */
	public Button.OnClickListener deleteBtnCallback = new Button.OnClickListener(){

		@Override
		public void onClick(View v) {
			IntegrateQuestInfo integrateQuestInfo = new IntegrateQuestInfo();
			integrateQuestInfo.setEnterpriseID(enterpriseId);
			integrateQuestInfo.setSdID(sdID);

			progressDialog = ProgressDialog.show(MyDemandDetailActivity.this,
					getString(R.string.alert_title),
					getString(R.string.alert_message), true, false);
			
			DeleteSupplyAsyn deleteSupplyAsyn = new DeleteSupplyAsyn();
			deleteSupplyAsyn.execute(integrateQuestInfo);
		}
		
	};
	
	/**
	 * 发布供应按钮点击事件
	 */
	public Button.OnClickListener releaseBtnCallback = new Button.OnClickListener(){

		@Override
		public void onClick(View v) {
			releaseBtn.setEnabled(false);
			//文本框不能为空,重要字段为空或为0时不可提交
			SupplyDemandDescInfo supplyDemandDescInfo = new SupplyDemandDescInfo();
			
			if (title.getText().toString().trim() == null || title.getText().toString().trim().equals("")) {
				Toast.makeText(MyDemandDetailActivity.this, "标题不可为空", Toast.LENGTH_LONG).show();
				releaseBtn.setEnabled(true);
				return;
			} else {
				supplyDemandDescInfo.setTitle(title.getText().toString().trim());
			}
			
			if (introduction.getText().toString().trim() == null || introduction.getText().toString().trim().equals("")) {
				Toast.makeText(MyDemandDetailActivity.this, "简介不可为空", Toast.LENGTH_LONG).show();
				releaseBtn.setEnabled(true);
				return;
			} else {
				supplyDemandDescInfo.setIntroduction(introduction.getText().toString().trim());
			}
			
			if (keywords.getText().toString().trim() == null || keywords.getText().toString().trim().equals("")) {
				Toast.makeText(MyDemandDetailActivity.this, "关键字不可为空", Toast.LENGTH_LONG).show();
				releaseBtn.setEnabled(true);
				return;
			} else {
				supplyDemandDescInfo.setKeyWords(keywords.getText().toString().trim());
			}
			
			if (productInfo.getText().toString().trim() == null || productInfo.getText().toString().trim().equals("") ) {
				Toast.makeText(MyDemandDetailActivity.this, "详细内容不可为空", Toast.LENGTH_LONG).show();
				releaseBtn.setEnabled(true);
				return;
			} else {
				supplyDemandDescInfo.setDescription(productInfo.getText().toString().trim());
			}
			
			if (enterpriseId == 0) {
				Toast.makeText(MyDemandDetailActivity.this, "未获取到有效单位ID", Toast.LENGTH_LONG).show();
				releaseBtn.setEnabled(true);
				return;
			} else {
				supplyDemandDescInfo.setEnterpriseID(enterpriseId);
			}
			
			if (date == null || date.equals("")) {
				Toast.makeText(MyDemandDetailActivity.this, "请选择截止日期", Toast.LENGTH_LONG).show();
				releaseBtn.setEnabled(true);
				return;
			} else {
				supplyDemandDescInfo.setTimeDown(date);
			}
			
			if (sdID == 0) {
				Toast.makeText(MyDemandDetailActivity.this, "未获取到有效产品ID", Toast.LENGTH_LONG).show();
				releaseBtn.setEnabled(true);
				return;
			} else {
				supplyDemandDescInfo.setSdID(sdID);
			}
			
			try {
				List<PicturesInfo> picInfos =picGrid.getList();
				
				fPhotoInfos = new ArrayList<FPhotoInfo>();
				
				if (picInfos == null || picInfos.size() == 0) {
					
				} else {
					for (int i = 0; i < picInfos.size(); i++) {
						PicturesInfo picturesInfo = picInfos.get(i);
						FPhotoInfo info = new FPhotoInfo();
						
						if (picturesInfo.getPhotoNormal() == null || picturesInfo.getPhotoNormal().equals("")) {
							info.setPhotoPathNormal(picturesInfo.getPureName());
							info.setPhotoName(picturesInfo.getPureName());
						} else {
							info.setPhotoPathNormal(picturesInfo.getPhotoNormal());
							info.setPhotoName(picturesInfo.getPhotoNormal());
						}
						
						if (picturesInfo.getPhotoSmall() == null || picturesInfo.getPhotoSmall().equals("")) {
							info.setPhotoPathSmall(picturesInfo.getSurl());
						} else {
							info.setPhotoPathSmall(picturesInfo.getPhotoSmall());
						}
						
						info.setPhotoDescription(picturesInfo.getDescription());
						
						fPhotoInfos.add(info);
					}
					supplyDemandDescInfo.setPhotoList(fPhotoInfos);
				}
			} catch (Exception e) {
				Toast.makeText(MyDemandDetailActivity.this, "图片未保存成功", Toast.LENGTH_LONG).show();
				e.printStackTrace();
			}
			
			supplyDemandDescInfo.setTypeCode(1);
			supplyDemandDescInfo.setStatus(0);
			
			progressDialog = ProgressDialog.show(MyDemandDetailActivity.this,
					getString(R.string.alert_title),
					getString(R.string.alert_message), true, false);
			
			ReleaseSupplyAsyn releaseSupplyAsyn = new ReleaseSupplyAsyn();
			releaseSupplyAsyn.execute(supplyDemandDescInfo);
		}
		
	};
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == 0 || requestCode == 1) {
				// 和之前的图片区分, 这个需求大图和小图都要上传
				picGrid.onViewResult(requestCode, resultCode, data,2,2);
			} 
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	/**
	 * 时间选择按钮点击事件
	 */
	public Button.OnClickListener dateBtnCallback = new Button.OnClickListener(){

		@Override
		public void onClick(View v) {
			showDialog(0);
		}
		
	};
	/**
     * 创建日期及时间选择对话框
     */
    @Override
    protected Dialog onCreateDialog(int id) {
    	Dialog dialog = null;
        switch (id) {
        case 0:
            Calendar c = Calendar.getInstance();
            dialog = new DatePickerDialog(
                this,
                new DatePickerDialog.OnDateSetListener() {
                    public void onDateSet(DatePicker dp, int year,int month, int dayOfMonth) {
                    	
                        Date curDate = new Date(System.currentTimeMillis());
                       /* int i = curDate.getYear() + 1900;
                        int j = curDate.getMonth() + 1;
                        int k = curDate.getDate();*/
                        if (year > (curDate.getYear() + 1900)) {
                        	datePicker.setText(year + "-" + (month+1) + "-" + dayOfMonth);
                            date = year + "-" + (month+1) + "-" + dayOfMonth;
						} else if (year == (curDate.getYear() + 1900)) {
							if ((month+1) > (curDate.getMonth() + 1)) {
								datePicker.setText(year + "-" + (month+1) + "-" + dayOfMonth);
	                            date = year + "-" + (month+1) + "-" + dayOfMonth;
							} else if ((month+1) == (curDate.getMonth() + 1)) {
								if (dayOfMonth >= curDate.getDate()) {
									datePicker.setText(year + "-" + (month+1) + "-" + dayOfMonth);
		                            date = year + "-" + (month+1) + "-" + dayOfMonth;
								} else {
									Toast.makeText(MyDemandDetailActivity.this, getString(R.string.date_error), Toast.LENGTH_LONG).show();
								}
							} else {
								Toast.makeText(MyDemandDetailActivity.this, getString(R.string.date_error), Toast.LENGTH_LONG).show();
							}
						} else {
							Toast.makeText(MyDemandDetailActivity.this, getString(R.string.date_error), Toast.LENGTH_LONG).show();
						}
                    }
                }, 
                c.get(Calendar.YEAR), // 传入年份
                c.get(Calendar.MONTH), // 传入月份
                c.get(Calendar.DAY_OF_MONTH) // 传入天数
            );
            break;
        }
		return dialog;
    	
    }
	
	public void showFinishDialog(String s,String string){
    	new AlertDialog.Builder(MyDemandDetailActivity.this).setTitle(s)
		.setMessage(string).setPositiveButton("确定", new DialogInterface.OnClickListener() {
	
			@Override
			public void onClick(DialogInterface dialog, int which) {
				MyDemandDetailActivity.this.finish();
			}
		}).create().show();
    }
	
	/**
	 * 返回按钮点击事件。如果处于编辑状态则返回初始化状态，即放弃编辑。
	 * 如果处于查看信息状态，则退出此页
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			MyDemandDetailActivity.this.finish();
			return true;
			
		}
		return super.onKeyDown(keyCode, event);
	}


	/**
	 * 编辑后再发布的异步
	 * @author Maniac
	 * 2012.12.12
	 */
	private class ReleaseSupplyAsyn extends MyAsyncTask{
		private SupplyDemandDescInfo request;
		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(MyDemandDetailActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				
				Message message = (Message) Utils.fromJSON((String) res, Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(MyDemandDetailActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG).show();
				} else {
					ResultInfo resultInfo = (ResultInfo)Utils.fromJSON(string, ResultInfo.class);
					int result = resultInfo.getResult();
					if (result == 7310) {
						Intent intent = new Intent();
						String newString = Utils.toJSON(request);
						intent.putExtra("editedInfo", newString);
						setResult(100,intent);
						Toast.makeText(MyDemandDetailActivity.this, resultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
						MyDemandDetailActivity.this.finish();
						Utils.randomAnim(MyDemandDetailActivity.this);
					} else {
						Toast.makeText(MyDemandDetailActivity.this, resultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
					}
				}
			}
			releaseBtn.setEnabled(true);
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			request = (SupplyDemandDescInfo)params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(7300, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
	}
	
	/**
	 * 删除当前信息异步
	 * @author Maniac
	 */
	private class DeleteSupplyAsyn extends MyAsyncTask{

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(MyDemandDetailActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				
				Message message = (Message) Utils.fromJSON((String) res, Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(MyDemandDetailActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG).show();
				} else {
					ResultInfo resultInfo = (ResultInfo)Utils.fromJSON(string, ResultInfo.class);
					int result = resultInfo.getResult();
					if (result == 7410) {
						
						//返回列表activity 并删除该项
						setResult(200);
						
						Toast.makeText(MyDemandDetailActivity.this, resultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
						MyDemandDetailActivity.this.finish();
						Utils.randomAnim(MyDemandDetailActivity.this);
						
					} else {
						Toast.makeText(MyDemandDetailActivity.this, resultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			IntegrateQuestInfo request = (IntegrateQuestInfo)params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(7400, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
		
	}
}
